import  requests
import  json
import  time
import  random
import  hashlib  #进行md5算法用于算出sign

class Youdao():
    # 创建所需的初始化属性
    # data  数据中有salt、sign、lts这三个数据是变化值
    # salt: 时间戳（int(time.time()*1000)）
    # lts : 时间戳+个位数随机数str(int(time.time()*1000))+str(random.randint(1,10))
    def __init__(self,word):
        self.url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36"
        }
        self.word = word
        self.salt = str(int(time.time()*1000))
        self.lts  = self.salt+str(random.randint(1,10))
        self.client = 'fanyideskweb'
        # 构建sign参数（通过自定义的md5方法）
        self.sign = self.md5(f'{self.client}{self.salt}{self.lts}Tbh5E8=q6U3EXe+&L[4c@')
        self.data = {
            "i": word,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": self.salt ,
            "sign": self.sign,
            "lts": self.lts,
            'bv': "7b7290f9dbb825e1eb29882d0b1fd770",
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTlME"
        }

    # 获取响应对象
    def post_data(self):
        response = requests.post(self.url,data = self.data,headers = self.headers)
        # print(response.content)
        return response.content

    # 解析数据
    def parse_data(self,data):
        data = json.loads(data)
        # print(data,type(data))
        # 从字典中抽取结果数据tgt
        try:
            word_tat = data['translateResult'][0]
            for word in word_tat:
                # print(worc['src'])
                print(word['tgt'])
        except Exception as e:
            print(f"抱歉有道翻译已经升级了！{e}")
            return None

    def md5(self,keyword):
        # 创建md5对象
        m = hashlib.md5()
        # 将字符串转换成byte类型
        b = keyword.encode(encoding='utf-8')
        # 加密字符串
        m.update(b)
        # 获取加密的字符串(32位)
        md5_str = m.hexdigest()
        # print(md5_str)
        return md5_str

    # 运行的方法
    def run(self):
        '''
        运行的步骤
            1、url（需要请求的有道翻译的url）
            2、发送请求获取响应对象response
            3、对数据进行解析
            4、输出字符串结果
        '''
        data = self.post_data()
        self.parse_data(data)
        # 可以打印出来观察那三个参数的变化
        # print(self.data)


if __name__ == '__main__':
    word = input("请输入你所需要翻译的文字:\t")
    youdao = Youdao(word)
    youdao.run()